#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>

//变换部分大部分通过看讲解完成

bool only_alpha(string s);


int main(int argc, string argv[])
{

    string key = argv[1];
    // 判断有没有输入东西,输入的是不是字母
    if (argc != 2 || only_alpha(key) == false)
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }

    // 判断有没有输入26个字母
    if (strlen(key) != 26 && only_alpha(key) == true)
    {
        printf("Key must contain 26 characters.\n");
        return 1;
    }

    int count[26] = {0};

    // 不能有重复的字母，并且先转换成小写并比较
    for (int i = 0; key[i] != '\0'; i++)
    {
        char c = key[i];
        if (isalpha(c) == false)
        {
            printf("Key must contain alphabetic characters.\n");
            return 1;
        }
        c = tolower(c);
        if (count[c - 'a'] > 0)
        {
            printf("Key must not contain duplicate characters.\n");
            return 1;
        }

        count[c - 'a']++;
    }

    // 获取用户输入的明文
    string plaintext = get_string("plaintext: ");
    string ciphertext = plaintext;

    for (int m = 0; plaintext[m] != 0; m++)
    {
        if (islower(plaintext[m]))
        {
            int index = plaintext[m] - 'a';
            char c = key[index];

            ciphertext[m] = tolower(c);
        }
        else if (isupper(plaintext[m]))
        {
            int index = plaintext[m] - 'A';
            char c = key[index];

            ciphertext[m] = toupper(c);
        }
    }

    printf("ciphertext: %s\n", ciphertext);
}

bool only_alpha(string s)
{
    bool only_alpha = false;
    for (int i = 0; s[i] != '\0'; i++)
    {
        if (isalpha(s[i]))
        {
            only_alpha = true;
        }
    }

    return only_alpha;
}
